import json
import os


def is_in_range(start, end, value):
    """
    Check if the value is in the range of start and end,and return the adjusted value
    :param start: 范围的左值
    :param end: 范围的右值
    :param value: 需要判断的值
    :return: 调整后的值
    """
    if start <= value <= end:
        return True, value
    elif value < start:
        return False, start
    else:
        return False, end


def intersection(rect1, rect2):
    # rect1 and rect2 are tuples of four points: (x1, y1, x2, y2, x3, y3, x4, y4)
    # We assume the points are given in clockwise order

    # Find the boundaries of the first rectangle
    x1_min, y1_min = min(rect1[0], rect1[2], rect1[4], rect1[6]), min(
        rect1[1], rect1[3], rect1[5], rect1[7]
    )
    x1_max, y1_max = max(rect1[0], rect1[2], rect1[4], rect1[6]), max(
        rect1[1], rect1[3], rect1[5], rect1[7]
    )

    # Find the boundaries of the second rectangle
    x2_min, y2_min = min(rect2[0], rect2[2], rect2[4], rect2[6]), min(
        rect2[1], rect2[3], rect2[5], rect2[7]
    )
    x2_max, y2_max = max(rect2[0], rect2[2], rect2[4], rect2[6]), max(
        rect2[1], rect2[3], rect2[5], rect2[7]
    )

    # Calculate the intersection boundaries
    x_min = max(x1_min, x2_min)
    y_min = max(y1_min, y2_min)
    x_max = min(x1_max, x2_max)
    y_max = min(y1_max, y2_max)

    # If there is no intersection, return None
    if x_min >= x_max or y_min >= y_max:
        return None

    # Return the intersection points
    return [(x_min, y_min), (x_max, y_min), (x_max, y_max), (x_min, y_max)]


if __name__ == "__main__":
    obj_dir = "./json_dir/"
    name_list = os.listdir(obj_dir)
    for name1 in name_list:
        if name1.split(".")[1] == "json":
            img_path = obj_dir + name1.split(".")[0] + ".jpg"
            json_path = obj_dir + name1.split(".")[0] + ".json"
            txt_path = obj_dir + name1.split(".")[0] + ".txt"

            row_list = []
            with open(json_path) as f:
                dict1 = json.load(f)
                imageWidth = dict1["imageWidth"]
                imageHeight = dict1["imageHeight"]
                img_name = dict1["imagePath"]
                shapes = dict1["shapes"]
                rect_image = (
                    0,
                    0,
                    1,
                    0,
                    1,
                    1,
                    0,
                    1,
                )
                for shape in shapes:
                    if shape["label"] == "WHITE_LABEL":
                        x1 = shape["points"][0][0] / imageWidth
                        y1 = shape["points"][0][1] / imageHeight
                        x2 = shape["points"][1][0] / imageWidth
                        y2 = shape["points"][1][1] / imageHeight
                        x3 = shape["points"][2][0] / imageWidth
                        y3 = shape["points"][2][1] / imageHeight
                        x4 = shape["points"][3][0] / imageWidth
                        y4 = shape["points"][3][1] / imageHeight

                        rect1 = (x1, y1, x2, y2, x3, y3, x4, y4)
                        final_rect = intersection(rect_image, rect1)
                        center_x = (final_rect[0][0] + final_rect[2][0]) / 2
                        center_y = (final_rect[0][1] + final_rect[2][1]) / 2
                        width = final_rect[2][0] - final_rect[0][0]
                        height = final_rect[2][1] - final_rect[0][1]

                        row1 = [
                            0,
                            center_x,
                            center_y,
                            width,
                            height,
                        ]
                        row1 = list(map("{:.6f}".format, row1))
                        row1[0] = 0
                        row_list.append(row1)

            with open(txt_path, "w", newline="") as f:
                for row in row_list:
                    for data in row:
                        f.write(str(data))
                        f.write(" ")
                    f.write("\r\n")
